package com.eatme.web.sys.quartz.config;

import com.eatme.web.sys.quartz.job.MyJob;
import com.eatme.web.sys.quartz.listener.AppJobListener;
import com.eatme.web.sys.quartz.listener.AppSchedulerListener;
import com.eatme.web.sys.quartz.listener.AppTriggerListener;
import org.quartz.*;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.quartz.QuartzProperties;
import org.springframework.boot.autoconfigure.quartz.SchedulerFactoryBeanCustomizer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.util.Map;
import java.util.Properties;

@Configuration
public class QuartzConfig {

    private Properties asProperties(Map<String, String> source) {
        Properties properties = new Properties();
        properties.putAll(source);
        return properties;
    }


//    @Resource
//    private AppJobFactory appJobFactory;

//    @Bean
//    public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
//        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
//        factoryBean.setDataSource(dataSource);
//        factoryBean.setJobFactory(appJobFactory);
//        // 程序启动后xx秒后开始执行quartz
//        factoryBean.setStartupDelay(2);
//
//        return factoryBean;
//    }


//    @Bean
//    public Scheduler scheduler(@Qualifier("scheduler")Scheduler scheduler) throws Exception {
//        scheduler.getListenerManager().addSchedulerListener(schedulerListener());
//        scheduler.getListenerManager().addTriggerListener(triggerListener());
//        scheduler.getListenerManager().addJobListener(jobListener());
//        return scheduler;
//    }

    // @Bean
    public SchedulerFactoryBean quartzScheduler(QuartzProperties properties, ObjectProvider<SchedulerFactoryBeanCustomizer> customizers, ObjectProvider<JobDetail> jobDetails, Map<String, Calendar> calendars, ObjectProvider<Trigger> triggers, ApplicationContext applicationContext) throws SchedulerException {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setGlobalJobListeners(jobListener());
        schedulerFactoryBean.setGlobalTriggerListeners(triggerListener());
        SpringBeanJobFactory jobFactory = new SpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        schedulerFactoryBean.setJobFactory(jobFactory);
        if (properties.getSchedulerName() != null) {
            schedulerFactoryBean.setSchedulerName(properties.getSchedulerName());
        }
        schedulerFactoryBean.setAutoStartup(properties.isAutoStartup());
        schedulerFactoryBean.setStartupDelay((int)properties.getStartupDelay().getSeconds());
        schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown(properties.isWaitForJobsToCompleteOnShutdown());
        schedulerFactoryBean.setOverwriteExistingJobs(properties.isOverwriteExistingJobs());
        if (!properties.getProperties().isEmpty()) {
            schedulerFactoryBean.setQuartzProperties(this.asProperties(properties.getProperties()));
        }

        schedulerFactoryBean.setJobDetails((JobDetail[])jobDetails.orderedStream().toArray((x$0) -> {
            return new JobDetail[x$0];
        }));
        schedulerFactoryBean.setCalendars(calendars);
        schedulerFactoryBean.setTriggers((Trigger[])triggers.orderedStream().toArray((x$0) -> {
            return new Trigger[x$0];
        }));
        customizers.orderedStream().forEach((customizer) -> {
            customizer.customize(schedulerFactoryBean);
        });
        return schedulerFactoryBean;
    }

    /**
     * 声明一个任务
     * @return
     */
     @Bean
    public JobDetail jobDetail() {
        return JobBuilder.newJob(MyJob.class)
                .withIdentity("MyJob","default")
                .storeDurably()
                .build();
    }
    /**
     * 声明一个触发器,什么时候触发这个任务
     * @return
     */
     @Bean
    public Trigger trigger() {
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail())
                .withIdentity("trigger","default")
                .startNow()
                // .withSchedule(CronScheduleBuilder.cronSchedule("*/2 * * * * ?"))
                .withSchedule(SimpleScheduleBuilder
                        .simpleSchedule()
                        .withIntervalInSeconds(5)
                        .withRepeatCount(5)
                )
                .build();
    }

    @Bean
    public TriggerListener triggerListener() {
         return new AppTriggerListener();
    }


    @Bean
    public JobListener jobListener() {
         return new AppJobListener();
    }

    @Bean
    public SchedulerListener schedulerListener() {
         return new AppSchedulerListener();
    }


}
